package com.dmz.wxcp.wecom.wxbusiness.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmz.wxcp.utils.DataResult;
import com.dmz.wxcp.vo.req.ProductReqVO;
import com.dmz.wxcp.vo.resp.PageRespVO;
import com.dmz.wxcp.wecom.common.LoginService;
import com.dmz.wxcp.wecom.contact.entity.Contact;
import com.dmz.wxcp.wecom.contact.mapper.ContactMapper;
import com.dmz.wxcp.wecom.signature.service.MP_OAuth2Service;
import com.dmz.wxcp.wecom.wxbusiness.entity.Article;
import com.dmz.wxcp.wecom.wxbusiness.entity.ArticleTags;
import com.dmz.wxcp.wecom.wxbusiness.entity.TagRecord;
import com.dmz.wxcp.wecom.wxbusiness.mapper.ArticleMapper;
import com.dmz.wxcp.wecom.wxbusiness.mapper.ArticleTagsMapper;
import com.dmz.wxcp.wecom.wxbusiness.mapper.PurchasingPriceMapper;
import com.dmz.wxcp.wecom.wxbusiness.service.ArticleService;
import com.dmz.wxcp.wecom.wxbusiness.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping("/mywechat")
public class IndexController {


    @Autowired
    private PurchasingPriceMapper purchasingPriceMapper;


    @Autowired
    private LoginService loginService;

    @Autowired
    private ContactMapper contactMapper;

    @Autowired
    private ArticleMapper articleMapper;

//    @Autowired
//    private ContactService contactService;

    @Autowired
    private IndexService indexService;

    @Autowired
    private ArticleTagsMapper tagsMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private MP_OAuth2Service cpOAuth2Service;




    @PostMapping("/getprice")
    @ResponseBody
    public DataResult GetPrice(@RequestBody HashMap<String,Object> map){
        ProductReqVO vo=new ProductReqVO();
        String productName=map.get("productName")!=null?map.get("productName").toString():"";
        String categoryName=map.get("categoryName")!=null?map.get("categoryName").toString():"";
        String productNum=map.get("productNum")!=null?map.get("productNum").toString():"";
        vo.setCurrentPage(new Long(map.get("page").toString()));
        vo.setPageSize(new Long(map.get("limit").toString()));

        vo.setCategoryName(categoryName);
        vo.setProductName(productName);
        vo.setProductNum(productNum);
//       获取并 拆解对象
        PageRespVO<Object> pageRespVO= indexService.getPriceObject(vo);
        return DataResult.success(pageRespVO.getTotal(),pageRespVO.getRecords());
    }

    @GetMapping("/articlelist")
    public String articleList(){
        return "articlelist";
    }

    @RequestMapping("/article")
    @ResponseBody
    public DataResult articlelist(@RequestParam Map<String,Object> map){
        IPage<Article> page = new Page<>();
        page.setCurrent(new Long(map.get("page").toString()));
        page.setSize(new Long(map.get("limit").toString()));
        IPage<Article> articles=articleMapper.getArticleList(page);
        QueryWrapper<Article> queryWrapper= Wrappers.query();
        queryWrapper.isNotNull("id");
        Integer totle=articleMapper.selectCount(queryWrapper);
        Double pages=Math.ceil(totle*1.0/page.getSize());
        articles.setSize(pages.longValue());
        return DataResult.success(articles);
    }


    /*
    文章详情控制器
     */
    @RequestMapping("/articledetail")
    public String articleDetail(@RequestParam Map<String,Object> map, Model model, HttpServletRequest request){
        Contact contact=(Contact)request.getSession().getAttribute("contact");
        Long id=new Long(map.get("id").toString());
        Article article=articleMapper.getArticleDetail(id);
//        更新浏览量
        articleService.updatePageViewRecord(id,contact);
//        articleService.UpdateArticlePageView(id);
////        添加浏览记录
//        ReadRecord record=new ReadRecord();
//        record.setArticleid(id);
//        record.setContactid(contact.getContactId());
//        articleService.InsertReadRecord(record);

        String [] imglist=article.getImages().split("\\|_\\|");
        model.addAttribute("article",article);
        model.addAttribute("images",imglist);
        return "productarticledetail";
    }

    @RequestMapping("/studyarticledetail")
    public String studyArticleDetail(@RequestParam Map<String,Object> map,Model model){
        Long id=new Long(map.get("id").toString());
        Article article=articleMapper.getStudyArticleDetail(id);
        String [] imglist=article.getImages().split("\\|_\\|");
        model.addAttribute("article",article);
        return "studyarticledetail";
    }

    @GetMapping("/homeindex")
    public String articleIndex(Model model){

//        1.获取首页的推荐文章列表
        List<Article> productArticles=articleMapper.getProductDisplayArticles();
        List<Article> studyArticles=articleMapper.getStudyDisplayArticles();
        model.addAttribute("productarticles",productArticles);
        model.addAttribute("studyarticles",studyArticles);
//        2.获取今日的小知识
        return "homeindex";
    }


    @RequestMapping("/searchtags")
    @ResponseBody
    public DataResult searchTags(@RequestParam Map<String,Object>map,HttpServletRequest request){
        Contact contact=(Contact)request.getSession().getAttribute("contact");
        String tagname=map.get("tagname").toString();
        Integer type=new Integer(map.get("type").toString());
//        查询是否有标签
        ArticleTags tag=tagsMapper.SelectCountNum(tagname,type);
//        如果有就在标签的点击数量上加1
        if(tag!=null){
            Integer b=tagsMapper.upDateClickTime(tagname);
            if(b>0){
                TagRecord tagRecord=new TagRecord();
                tagRecord.setContactid(contact.getContactId());
                tagRecord.setTagid(tag.getId());
                articleService.InsertTagRecord(tagRecord);

                return DataResult.success();
                //        添加标签搜索记录

            }else{
                return DataResult.getResult(30011001,"标签点击自增错误");
            }
//            如果没有就新建标签
        }else{
//            新增一个标签 返回主键
            tag=new ArticleTags(tagname,type);
            tagsMapper.InsertTag(tag);
            Long id=tag.getId();
            if(id!=null){
                //        添加标签搜索记录
                TagRecord tagRecord=new TagRecord();
                tagRecord.setContactid(contact.getContactId());
                tagRecord.setTagid(tag.getId());
                tagRecord.setType(tag.getType());
                articleService.InsertTagRecord(tagRecord);
                return DataResult.success();
            }else{
                return DataResult.getResult(30011001,"新增标签错误");
            }
        }
    }
}
